<!DOCTYPE HTML>
<html>

<head>
	<link rel="bookmark"  type="image/x-icon"  href="/img/logo_miccall.png"/>
	<link rel="shortcut icon" href="/img/logo_miccall.png">
	
			    <title>
    Ame雨
    </title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
    <link rel="stylesheet" href="/amelin-ting/css/mic_main.css" />
    <link rel="stylesheet" href="/amelin-ting/css/dropdownMenu.css" />
    <meta name="keywords" content="Ame雨" />
    
    	<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
	 
    <noscript>
        <link rel="stylesheet" href="/amelin-ting/css/noscript.css" />
    </noscript>
    <style type="text/css">
        body:before {
          content: ' ';
          position: fixed;
          top: 0;
          background: url('/amelin-ting/img/bg.jpg') center 0 no-repeat;
          right: 0;
          bottom: 0;
          left: 0;
          background-size: cover; 
        }
    </style>

			    
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script async type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


    <script src="/amelin-ting/js/jquery.min.js"></script>
    <script src="/amelin-ting/js/jquery.scrollex.min.js"></script>
    <script src="/amelin-ting/js/jquery.scrolly.min.js"></script>
    <script src="/amelin-ting/js/skel.min.js"></script>
    <script src="/amelin-ting/js/util.js"></script>
    <script src="/amelin-ting/js/main.js"></script>
	
<meta name="generator" content="Hexo 5.4.0"></head>
    
		
<!-- Layouts -->



<!--  代码渲染  -->
<link rel="stylesheet" href="/css/prism_coy.css" />
<link rel="stylesheet" href="/css/typo.css" />
<!-- 文章页 -->
<body class="is-loading">
    <!-- Wrapper 外包 s-->
    <div id="wrapper" class="fade-in">
        <!-- Intro 头部显示 s -->
        <!-- Intro 头部显示 e -->
        <!-- Header 头部logo start -->
        <header id="header">
    <a href="/amelin-ting/" class="logo">Art Space</a>
</header>
        <!-- Nav 导航条 start -->
        <nav id="nav" class="special" >
            <ul class="menu links" >
			<!-- Homepage  主页  --> 
			<li >
	            <a href="/amelin-ting/" rel="nofollow">主页</a>
	        </li>
			<!-- categories_name  分类   --> 
	        
	        <li class="active">
	            <a href="#s1">分类</a>
	                    <ul class="submenu">
	                        <li>
	                        <a class="category-link" href="/amelin-ting/categories/Go/">Go</a></li><li><a class="category-link" href="/amelin-ting/categories/django/">django</a></li><li><a class="category-link" href="/amelin-ting/categories/drf/">drf</a></li><li><a class="category-link" href="/amelin-ting/categories/gin/">gin</a></li><li><a class="category-link" href="/amelin-ting/categories/go/">go</a></li><li><a class="category-link" href="/amelin-ting/categories/linux/">linux</a></li><li><a class="category-link" href="/amelin-ting/categories/mysql/">mysql</a></li><li><a class="category-link" href="/amelin-ting/categories/python/">python</a></li><li><a class="category-link" href="/amelin-ting/categories/%E5%86%85%E7%BD%91%E7%A9%BF%E9%80%8F/">内网穿透</a></li><li><a class="category-link" href="/amelin-ting/categories/%E5%89%8D%E7%AB%AF/">前端</a>
	                    </ul>
	        </li>
	        
	        <!-- archives  归档   --> 
	        
	        
		        <!-- Pages 自定义   -->
		        
		        <li>
		            <a href="/about/" title="简历">
		                简历
		            </a>
		        </li>
		        
		        <li>
		            <a href="/group/" title="团队">
		                团队
		            </a>
		        </li>
		        
		        <li>
		            <a href="/gallery/" title="图库">
		                图库
		            </a>
		        </li>
		        
		        <li>
		            <a href="/tag/" title="标签">
		                标签
		            </a>
		        </li>
		        


            </ul>
            <!-- icons 图标   -->
			<ul class="icons">
                    
                    <li>
                        <a title="github" href="https://github.com/miccall" target="_blank" rel="noopener">
                            <i class="icon fa fa-github"></i>
                        </a>
                    </li>
                    
                    <li>
                        <a title="500px" href="http://500px.com" target="_blank" rel="noopener">
                            <i class="icon fa fa-500px"></i>
                        </a>
                    </li>
                    
			</ul>
</nav>

        <div id="main" >
            <div class ="post_page_title_img" style="height: 25rem;background-image: url(https://img2.baidu.com/it/u=1918731617,3579143187&amp;fm=26&amp;fmt=auto);background-position: center; background-repeat:no-repeat; background-size:cover;-moz-background-size:cover;overflow:hidden;" >
                <a href="#" style="padding: 4rem 4rem 2rem 4rem ;"><h2 >drf请求与响应</h2></a>
            </div>
            <!-- Post -->
            <div class="typo" style="padding: 3rem;">
                <h2 id="一、请求和响应"><a href="#一、请求和响应" class="headerlink" title="一、请求和响应"></a>一、请求和响应</h2><h3 id="1、请求"><a href="#1、请求" class="headerlink" title="1、请求"></a>1、请求</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># from rest_framework.request import Request</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, request, parsers=<span class="literal">None</span>, authenticators=<span class="literal">None</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">                  negotiator=<span class="literal">None</span>, parser_context=<span class="literal">None</span></span>):</span></span><br><span class="line">        </span><br><span class="line"><span class="comment"># 二次封装request, request作为drf request对象的_request 属性</span></span><br><span class="line">     self._request = request</span><br><span class="line">     <span class="function"><span class="keyword">def</span> <span class="title">__getattr__</span>（<span class="title">self</span>，<span class="title">item</span>）：</span></span><br><span class="line"><span class="function">        <span class="title">return</span> <span class="title">getattr</span>(<span class="params">self._request,item</span>) </span></span><br><span class="line"><span class="function">    </span></span><br><span class="line"><span class="function"># 请求对象.<span class="title">data</span>:</span>前端以三种编码方式传入的数据，都可以取出来。</span><br><span class="line"></span><br><span class="line"><span class="comment"># 请求对象.query_params 与Django标准的request.GET相同，只是更换了更正确的名称而已。</span></span><br></pre></td></tr></table></figure>

<h3 id="2、响应"><a href="#2、响应" class="headerlink" title="2、响应"></a>2、响应</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># from rest_framework.response import Response</span></span><br><span class="line">     <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, data=<span class="literal">None</span>, status=<span class="literal">None</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">                     template_name=<span class="literal">None</span>, headers=<span class="literal">None</span>,</span></span></span><br><span class="line"><span class="params"><span class="function">                     exception=<span class="literal">False</span>, content_type=<span class="literal">None</span></span>):</span></span><br><span class="line">        </span><br><span class="line">        </span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">    data:你要返回的数据，字典</span></span><br><span class="line"><span class="string">    satatus: 返回的状态码，默认是200</span></span><br><span class="line"><span class="string">        -from rest_framework import status在这个路径下，它把所有使用到的状态码都定义成了常量</span></span><br><span class="line"><span class="string">    template_name 渲染的模板名字(自定制模板),不需要了解</span></span><br><span class="line"><span class="string">    headers:响应头，可以往响应头放东西，就是一个字典。</span></span><br><span class="line"><span class="string">    content_type: 相应的编码格式， application/json和text/html；</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">浏览器响应成浏览器的格式，postman响应成json格式，通过配置实现的（默认配置）</span></span><br><span class="line"><span class="string">不管是postman还是浏览器，都返回json格式数据</span></span><br><span class="line"><span class="string">drf有默认的配置文件---》先从项目的setting中找，找不到，采用默认的</span></span><br><span class="line"><span class="string">drf的配置信息，先从自己类中找--》项目的setting中找---》默认的找</span></span><br><span class="line"><span class="string">	-局部使用:对某个视图类有效</span></span><br><span class="line"><span class="string">        -在视图类中写如下</span></span><br><span class="line"><span class="string">            from rest_framework.renderers import JSONRenderer</span></span><br><span class="line"><span class="string">            @renderer_classes=[JSONRenderer,]</span></span><br><span class="line"><span class="string">            def get(self, request):</span></span><br><span class="line"><span class="string">            	pass</span></span><br><span class="line"><span class="string">    -全局使用：全局的视图类，所有请求，都有效</span></span><br><span class="line"><span class="string">    	-在setting.py中加入如下</span></span><br><span class="line"><span class="string">            REST_FRAMEWORK = &#123;</span></span><br><span class="line"><span class="string">                &#x27;DEFAULT_RENDERER_CLASSES&#x27;: (  # 默认响应渲染类</span></span><br><span class="line"><span class="string">                    &#x27;rest_framework.renderers.JSONRenderer&#x27;,  # json渲染器</span></span><br><span class="line"><span class="string">                    &#x27;rest_framework.renderers.BrowsableAPIRenderer&#x27;,  # 浏览API渲染器</span></span><br><span class="line"><span class="string">                )</span></span><br><span class="line"><span class="string">            &#125;</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="二、视图"><a href="#二、视图" class="headerlink" title="二、视图"></a>二、视图</h2><h3 id="1、基于APIViews的5种接口"><a href="#1、基于APIViews的5种接口" class="headerlink" title="1、基于APIViews的5种接口"></a>1、基于APIViews的5种接口</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># models.py</span></span><br><span class="line">    <span class="keyword">from</span> django.db <span class="keyword">import</span> models</span><br><span class="line">    <span class="comment"># Create your models here.</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Book</span>(<span class="params">models.Model</span>):</span></span><br><span class="line">        title = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">        price = models.DecimalField(max_digits=<span class="number">8</span>, decimal_places=<span class="number">2</span>)</span><br><span class="line">        publish = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">        author = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">        </span><br><span class="line"><span class="comment"># 在应用下面创建一个py文件，名字任意(ser.py)</span></span><br><span class="line">    <span class="keyword">from</span> rest_framework <span class="keyword">import</span> serializers</span><br><span class="line">    <span class="keyword">from</span> app01 <span class="keyword">import</span> models</span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">BookModelSerializer</span>(<span class="params">serializers.ModelSerializer</span>):</span></span><br><span class="line">        <span class="class"><span class="keyword">class</span> <span class="title">Meta</span>:</span></span><br><span class="line">            model = models.Book</span><br><span class="line">            fields = <span class="string">&#x27;__all__&#x27;</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># urls.py</span></span><br><span class="line">    <span class="keyword">from</span> app01 <span class="keyword">import</span> views</span><br><span class="line">    urlpatterns = [</span><br><span class="line">        url(<span class="string">r&#x27;^books/&#x27;</span>, views.BooksViews.as_view()),</span><br><span class="line">        url(<span class="string">r&#x27;^book/(?P&lt;pk&gt;\d+)&#x27;</span>, views.BookViews.as_view()),</span><br><span class="line">    ]</span><br><span class="line">    </span><br><span class="line"><span class="comment"># views.py</span></span><br><span class="line">    <span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render</span><br><span class="line">    <span class="keyword">from</span> rest_framework.views <span class="keyword">import</span> APIView</span><br><span class="line">    <span class="keyword">from</span> app01 <span class="keyword">import</span> models</span><br><span class="line">    <span class="keyword">from</span> app01 <span class="keyword">import</span> utils</span><br><span class="line">    <span class="keyword">from</span> app01 <span class="keyword">import</span> ser</span><br><span class="line">    <span class="keyword">from</span> rest_framework.response <span class="keyword">import</span> Response</span><br><span class="line">    <span class="comment"># Create your views here.</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">BooksViews</span>(<span class="params">APIView</span>):</span></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">get</span>(<span class="params">self, request</span>):</span></span><br><span class="line">            <span class="comment"># 返回字典db</span></span><br><span class="line">            response_dir = utils.MyResponse()</span><br><span class="line">            <span class="comment"># 拿到所有文章对象</span></span><br><span class="line">            book_queryset = models.Book.objects.<span class="built_in">all</span>()</span><br><span class="line">            <span class="comment"># 实例化</span></span><br><span class="line">            book_ser = ser.BookModelSerializer(book_queryset, many=<span class="literal">True</span>)</span><br><span class="line">            <span class="comment"># 字典更新</span></span><br><span class="line">            response_dir.data = book_ser.data</span><br><span class="line">            <span class="keyword">return</span> Response(response_dir.get_dir)</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">post</span>(<span class="params">self, request</span>):</span></span><br><span class="line">            <span class="comment"># 返回字典</span></span><br><span class="line">            response_dir = utils.MyResponse()</span><br><span class="line">            <span class="comment"># 实例化</span></span><br><span class="line">            book_ser = ser.BookModelSerializer(data=request.data)</span><br><span class="line">            <span class="keyword">if</span> book_ser.is_valid():</span><br><span class="line">                book_ser.save()</span><br><span class="line">                response_dir.data = book_ser.data</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                response_dir.status = <span class="number">201</span></span><br><span class="line">                response_dir.msg = <span class="string">&#x27;数据校验不通过&#x27;</span></span><br><span class="line">                response_dir.data = book_ser.errors</span><br><span class="line">            <span class="keyword">return</span> Response(response_dir.get_dir)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">BookViews</span>(<span class="params">APIView</span>):</span></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">get</span>(<span class="params">self, request, pk</span>):</span></span><br><span class="line">            response_dir = utils.MyResponse()</span><br><span class="line">            book_obj = models.Book.objects.<span class="built_in">filter</span>(pk=pk).first()</span><br><span class="line">            book_ser = ser.BookModelSerializer(book_obj)</span><br><span class="line">            response_dir.data = book_ser.data</span><br><span class="line">            <span class="keyword">return</span> Response(response_dir.get_dir)</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">delete</span>(<span class="params">self, request, pk</span>):</span></span><br><span class="line">            response_dir = utils.MyResponse()</span><br><span class="line">            models.Book.objects.<span class="built_in">filter</span>(pk=pk).delete()</span><br><span class="line">            <span class="keyword">return</span> Response(response_dir.get_dir)</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">put</span>(<span class="params">self, request, pk</span>):</span></span><br><span class="line">            response_dir = utils.MyResponse()</span><br><span class="line">            book_obj = models.Book.objects.<span class="built_in">filter</span>(pk=pk).first()</span><br><span class="line">            book_ser = ser.BookModelSerializer(instance=book_obj, data=request.data)</span><br><span class="line">            <span class="keyword">if</span> book_ser.is_valid():</span><br><span class="line">                book_ser.save()</span><br><span class="line">                response_dir.data = book_ser.data</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                response_dir.status = <span class="number">201</span></span><br><span class="line">                response_dir.msg = <span class="string">&#x27;数据校验不合格&#x27;</span></span><br><span class="line">                response_dir.data = book_ser.errors</span><br><span class="line">            <span class="keyword">return</span> Response(response_dir.get_dir)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h3 id="2、基于GenericAPIView的5种接口"><a href="#2、基于GenericAPIView的5种接口" class="headerlink" title="2、基于GenericAPIView的5种接口"></a>2、基于GenericAPIView的5种接口</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># views.py</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Book2View</span>(<span class="params">GenericAPIView</span>):</span></span><br><span class="line">        <span class="comment">#queryset要传queryset对象，查询了所有的图书</span></span><br><span class="line">        <span class="comment"># serializer_class使用哪个序列化类来序列化这堆数据</span></span><br><span class="line">        queryset=Book.objects</span><br><span class="line">        <span class="comment"># queryset=Book.objects.all()</span></span><br><span class="line">        serializer_class = BookSerializer</span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">get</span>(<span class="params">self,request</span>):</span></span><br><span class="line">            book_list=self.get_queryset()</span><br><span class="line">            book_ser=self.get_serializer(book_list,many=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">            <span class="keyword">return</span> Response(book_ser.data)</span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">post</span>(<span class="params">self,request</span>):</span></span><br><span class="line">            book_ser = self.get_serializer(data=request.data)</span><br><span class="line">            <span class="keyword">if</span> book_ser.is_valid():</span><br><span class="line">                book_ser.save()</span><br><span class="line">                <span class="keyword">return</span> Response(book_ser.data)</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">return</span> Response(&#123;<span class="string">&#x27;status&#x27;</span>:<span class="number">101</span>,<span class="string">&#x27;msg&#x27;</span>:<span class="string">&#x27;校验失败&#x27;</span>&#125;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Book2DetailView</span>(<span class="params">GenericAPIView</span>):</span></span><br><span class="line">        queryset = Book.objects</span><br><span class="line">        serializer_class = BookSerializer</span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">get</span>(<span class="params">self, request,pk</span>):</span></span><br><span class="line">            book = self.get_object()</span><br><span class="line">            book_ser = self.get_serializer(book)	</span><br><span class="line">            <span class="keyword">return</span> Response(book_ser.data)</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">put</span>(<span class="params">self, request,pk</span>):</span></span><br><span class="line">            book = self.get_object()</span><br><span class="line">            book_ser = self.get_serializer(instance=book,data=request.data)</span><br><span class="line">            <span class="keyword">if</span> book_ser.is_valid():</span><br><span class="line">                book_ser.save()</span><br><span class="line">                <span class="keyword">return</span> Response(book_ser.data)</span><br><span class="line">            <span class="keyword">else</span>:</span><br><span class="line">                <span class="keyword">return</span> Response(&#123;<span class="string">&#x27;status&#x27;</span>: <span class="number">101</span>, <span class="string">&#x27;msg&#x27;</span>: <span class="string">&#x27;校验失败&#x27;</span>&#125;)</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">delete</span>(<span class="params">self,request,pk</span>):</span></span><br><span class="line">            ret=self.get_object().delete()</span><br><span class="line">            <span class="keyword">return</span> Response(&#123;<span class="string">&#x27;status&#x27;</span>: <span class="number">100</span>, <span class="string">&#x27;msg&#x27;</span>: <span class="string">&#x27;删除成功&#x27;</span>&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment"># url.py</span></span><br><span class="line">    <span class="comment"># 使用GenericAPIView重写的</span></span><br><span class="line">    path(<span class="string">&#x27;books2/&#x27;</span>, views.Book2View.as_view()),</span><br><span class="line">    re_path(<span class="string">&#x27;books2/(?P&lt;pk&gt;\d+)&#x27;</span>, views.Book2DetailView.as_view()),</span><br></pre></td></tr></table></figure>

<h3 id="3、基于GenericAPIView和5个视图扩展类写的接口"><a href="#3、基于GenericAPIView和5个视图扩展类写的接口" class="headerlink" title="3、基于GenericAPIView和5个视图扩展类写的接口"></a>3、基于GenericAPIView和5个视图扩展类写的接口</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> rest_framework.mixins <span class="keyword">import</span> ListModelMixin,CreateModelMixin,UpdateModelMixin,DestroyModelMixin,RetrieveModelMixin</span><br><span class="line"><span class="comment"># views.py</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Book3View</span>(<span class="params">GenericAPIView,ListModelMixin,CreateModelMixin</span>):</span></span><br><span class="line"></span><br><span class="line">        queryset=Book.objects</span><br><span class="line">        serializer_class = BookSerializer</span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">get</span>(<span class="params">self,request</span>):</span></span><br><span class="line">            <span class="keyword">return</span> self.<span class="built_in">list</span>(request)</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">post</span>(<span class="params">self,request</span>):</span></span><br><span class="line">            <span class="keyword">return</span> self.create(request)</span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Book3DetailView</span>(<span class="params">GenericAPIView,RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin</span>):</span></span><br><span class="line">        queryset = Book.objects</span><br><span class="line">        serializer_class = BookSerializer</span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">get</span>(<span class="params">self, request,pk</span>):</span></span><br><span class="line">            <span class="keyword">return</span> self.retrieve(request,pk)</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">put</span>(<span class="params">self, request,pk</span>):</span></span><br><span class="line">            <span class="keyword">return</span> self.update(request,pk)</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">def</span> <span class="title">delete</span>(<span class="params">self,request,pk</span>):</span></span><br><span class="line">            <span class="keyword">return</span> self.destroy(request,pk)</span><br><span class="line"><span class="comment"># urls.py</span></span><br><span class="line">    <span class="comment"># 使用GenericAPIView+5 个视图扩展类  重写的</span></span><br><span class="line">    path(<span class="string">&#x27;books3/&#x27;</span>, views.Book3View.as_view()),</span><br><span class="line">    re_path(<span class="string">&#x27;books3/(?P&lt;pk&gt;\d+)&#x27;</span>, views.Book3DetailView.as_view()),	</span><br></pre></td></tr></table></figure>

<h3 id="4、GenericAPIView的视图子类-9个"><a href="#4、GenericAPIView的视图子类-9个" class="headerlink" title="4、GenericAPIView的视图子类(9个)"></a>4、GenericAPIView的视图子类(9个)</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> rest_framework.generics <span class="keyword">import</span> CreateAPIView, ListAPIView, RetrieveAPIView, UpdateAPIView, DestroyAPIView, ListCreateAPIView, RetrieveDestroyAPIView, RetrieveUpdateDestroyAPIView, RetrieveUpdateAPIView</span><br><span class="line"></span><br><span class="line"><span class="comment"># views.py</span></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">BooksViews</span>(<span class="params">ListCreateAPIView</span>):</span></span><br><span class="line">        queryset = models.Book.objects</span><br><span class="line">        serializer_class = ser.BookModelSerializer</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">BookViews</span>(<span class="params">RetrieveUpdateDestroyAPIView</span>):</span></span><br><span class="line">        queryset = models.Book.objects</span><br><span class="line">        serializer_class = ser.BookModelSerializer</span><br></pre></td></tr></table></figure>

<h3 id="5、-源码分析ViewSetMixin"><a href="#5、-源码分析ViewSetMixin" class="headerlink" title="5、 源码分析ViewSetMixin"></a>5、 源码分析ViewSetMixin</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 重写了as_view</span></span><br><span class="line"><span class="comment"># 核心代码（所以路由中只要配置了对应关系，比如&#123;&#x27;get&#x27;:&#x27;list&#x27;&#125;）,当get请求来，就会执行list方法</span></span><br><span class="line"><span class="keyword">for</span> method, action <span class="keyword">in</span> actions.items():</span><br><span class="line">    <span class="comment">#method：get</span></span><br><span class="line">    <span class="comment"># action：list</span></span><br><span class="line">    handler = <span class="built_in">getattr</span>(self, action)</span><br><span class="line">    <span class="comment">#执行完上一句，handler就变成了list的内存地址</span></span><br><span class="line">    <span class="built_in">setattr</span>(self, method, handler)</span><br><span class="line">    <span class="comment">#执行完上一句  对象.get=list</span></span><br><span class="line">    <span class="comment">#for循环执行完毕 对象.get:对着list   对象.post：对着create</span></span><br></pre></td></tr></table></figure>

<h3 id="6、继承ViewSetMixin的视图类"><a href="#6、继承ViewSetMixin的视图类" class="headerlink" title="6、继承ViewSetMixin的视图类"></a>6、继承ViewSetMixin的视图类</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># views.py</span></span><br><span class="line"><span class="keyword">from</span> rest_framework.viewsets <span class="keyword">import</span> ViewSetMixin</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Book6View</span>(<span class="params">ViewSetMixin,APIView</span>):</span> <span class="comment">#一定要放在APIVIew前</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_all_book</span>(<span class="params">self,request</span>):</span></span><br><span class="line">        <span class="built_in">print</span>(<span class="string">&quot;xxxx&quot;</span>)</span><br><span class="line">        book_list = Book.objects.<span class="built_in">all</span>()</span><br><span class="line">        book_ser = BookSerializer(book_list, many=<span class="literal">True</span>)</span><br><span class="line">        <span class="keyword">return</span> Response(book_ser.data)</span><br><span class="line">    </span><br><span class="line"><span class="comment"># urls.py</span></span><br><span class="line">    <span class="comment">#继承ViewSetMixin的视图类，路由可以改写成这样</span></span><br><span class="line">    path(<span class="string">&#x27;books6/&#x27;</span>, views.Book6View.as_view(actions=&#123;<span class="string">&#x27;get&#x27;</span>: <span class="string">&#x27;get_all_book&#x27;</span>&#125;)),</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="三、视图家族"><a href="#三、视图家族" class="headerlink" title="三、视图家族"></a>三、视图家族</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">-APIView---》继承自View</span></span><br><span class="line"><span class="string">-GenicAPIView---》APIView，做了一些扩展：</span></span><br><span class="line"><span class="string">	-queryset = None</span></span><br><span class="line"><span class="string">	-serializer_class = None</span></span><br><span class="line"><span class="string">	-get_queryset()  经常用</span></span><br><span class="line"><span class="string">	-get_serializer() 经常用</span></span><br><span class="line"><span class="string">	-get_serializer_class() 内部来用，外部会重写</span></span><br><span class="line"><span class="string">	-get_object()  经常用，获取一条数据（pk传过来）</span></span><br><span class="line"><span class="string">		-源码解析</span></span><br><span class="line"><span class="string">            queryset = self.filter_queryset(self.get_queryset()) #返回所有数据queryset对象</span></span><br><span class="line"><span class="string">            # lookup_url_kwarg就是pk，路由中有名分组分出来的pk</span></span><br><span class="line"><span class="string">            lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field</span></span><br><span class="line"><span class="string">            # &#123;pk:4&#125;  4 浏览器地址中要查询的id号http://127.0.0.1:8000/books6/4/</span></span><br><span class="line"><span class="string">            filter_kwargs = &#123;self.lookup_field: self.kwargs[lookup_url_kwarg]&#125;</span></span><br><span class="line"><span class="string">            # 根据pk=4去queryset中get单个对象</span></span><br><span class="line"><span class="string">            obj = get_object_or_404(queryset, **filter_kwargs)</span></span><br><span class="line"><span class="string">            self.check_object_permissions(self.request, obj)</span></span><br><span class="line"><span class="string">            return obj</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">5个视图扩展类（继承了object），每个里面写了一个方法（ListModelMixin：list方法）		</span></span><br><span class="line"><span class="string">        ListModelMixin,</span></span><br><span class="line"><span class="string">        CreateModelMixin,</span></span><br><span class="line"><span class="string">        UpdateModelMixin,</span></span><br><span class="line"><span class="string">        DestroyModelMixin,</span></span><br><span class="line"><span class="string">        RetrieveModelMixin</span></span><br><span class="line"><span class="string">GenericAPIView的视图子类，9个，继承了GenicAPIView+一个或者两个或者三个视图扩展类</span></span><br><span class="line"><span class="string">        CreateAPIView,</span></span><br><span class="line"><span class="string">        ListAPIView,</span></span><br><span class="line"><span class="string">        UpdateAPIView,</span></span><br><span class="line"><span class="string">        RetrieveAPIView,</span></span><br><span class="line"><span class="string">        DestroyAPIView,</span></span><br><span class="line"><span class="string">        ListCreateAPIView,</span></span><br><span class="line"><span class="string">        RetrieveUpdateDestroyAPIView,</span></span><br><span class="line"><span class="string">        RetrieveDestroyAPIView,</span></span><br><span class="line"><span class="string">        RetrieveUpdateAPIView</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">视图集：ModelViewSet,ReadOnlyModelViewSet：继承了上面一堆（5个视图扩展和GenicAPIView）+自己写了一个ViewSetMixin（as_view方法），只要继承它的，路由得写成&#123;‘get’：‘自己定义的方法’&#125;</span></span><br><span class="line"><span class="string">	-ViewSet=ViewSetMixin, views.APIView ：ViewSetMixin要放在前面</span></span><br><span class="line"><span class="string">    -GenericViewSet=ViewSetMixin+GenicAPIView</span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">    -ViewSetMixin（as_view方法）</span></span><br><span class="line"><span class="string">    -ViewSetMixin+APIView=ViewSet</span></span><br><span class="line"><span class="string">    -ViewSetMixin+GenicAPIView=GenericViewSet</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>


            </div>

            <!-- Post Comments -->
            
    <!-- 使用 DISQUS_CLICK -->
<div id="disqus-comment">
    <div id="disqus_thread"></div>

<!-- add animation -->
<style>
	.disqus_click_btn {
            line-height: 30px;
            margin: 0;
            min-width: 50px;
            padding: 0 14px;
            display: inline-block;
            font-family: "Roboto", "Helvetica", "Arial", sans-serif;
            font-size: 14px;
            font-weight: 400;
            text-transform: uppercase;
            letter-spacing: 0;
            overflow: hidden;
            will-change: box-shadow;
            transition: box-shadow .2s cubic-bezier(.4, 0, 1, 1), background-color .2s cubic-bezier(.4, 0, .2, 1), color .2s cubic-bezier(.4, 0, .2, 1);
            outline: 0;
            cursor: pointer;
            text-decoration: none;
            text-align: center;
            vertical-align: middle;
            border: 0;
            background: rgba(158, 158, 158, .2);
            box-shadow: 0 2px 2px 0 rgba(0, 0, 0, .14), 0 3px 1px -2px rgba(0, 0, 0, .2), 0 1px 5px 0 rgba(0, 0, 0, .12);
            color: #fff;
            background-color: #7EC0EE;
            text-shadow: 0
        }
</style>
	
<div class="btn_click_load" id="disqus_bt"> 
    <button class="disqus_click_btn">点击查看评论</button>
</div>

<!--
<script type="text/javascript">
$('.btn_click_load').click(function() {
    /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
    var disqus_shortname = 'http-miccall-tech'; // required: replace example with your forum shortname

    /* * * DON'T EDIT BELOW THIS LINE * * */
    (function() {
      var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
      dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
      (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();

    document.getElementById('disqus_bt').style.display = "none";
});
</script>
-->
<script type="text/javascript">
    var disqus_config = function () {
        this.page.url = 'https://gitee.com/AmeX/amelin-ting.git/2018/05/27/drf------%E8%AF%B7%E6%B1%82%E4%B8%8E%E5%93%8D%E5%BA%94/';  // Replace PAGE_URL with your page's canonical URL variable
        this.page.identifier = 'https://gitee.com/AmeX/amelin-ting.git/2018/05/27/drf------%E8%AF%B7%E6%B1%82%E4%B8%8E%E5%93%8D%E5%BA%94/'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
    };
</script>

<script type="text/javascript">
    $('.btn_click_load').click(function() {  //click to load comments
        (function() { // DON'T EDIT BELOW THIS LINE
            var d = document;
            var s = d.createElement('script');
            s.src = '//http-miccall-tech.disqus.com/embed.js';
            s.setAttribute('data-timestamp', + new Date());
            (d.head || d.body).appendChild(s);
        })();
        $('.btn_click_load').css('display','none');
    });
</script>
</div>
<style>
    #disqus-comment{
        background-color: #eee;
        padding: 2pc;
    }
</style>


        </div>
        <!-- Copyright 版权 start -->
                <div id="copyright">
            <ul>
                <li>&copy;Powered By <a target="_blank" rel="noopener" href="https://hexo.io/zh-cn/" style="border-bottom: none;">hexo</a></li>
                <li>Design: <a target="_blank" rel="noopener" href="http://miccall.tech " style="border-bottom: none;">miccall</a></li>
            </ul>
            
                <span id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
			
        </div>
    </div>
</body>



 	
</html>
